package array;

public class 转圈打印矩阵 {

	public static void main(String[] args) {
		int[][] arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } };
		// print(arr, 0, 0, arr.length - 1, arr[0].length - 1);
		printUnRec(arr);
		System.out.println("程序可以输出这句话，因为此程序可以正常结束");
	}

	public static void print(int[][] arr, int x1, int y1, int x2, int y2) {
		if (x2 < x1 || y2 < y1) {
			return;
		}
		for (int i = x1; i < x2; i++) {
			System.out.print(arr[y1][i] + " ");
		}
		for (int i = y1; i < y2; i++) {
			System.out.print(arr[i][x2] + " ");
		}
		for (int i = x2; i > x1; i--) {
			System.out.print(arr[y2][i] + " ");
		}
		for (int i = y2; i > y1; i--) {
			System.out.print(arr[i][x1] + " ");
		}
		print(arr, x1 + 1, y1 + 1, x2 - 1, y2 - 1);
	}

	public static void printUnRec(int[][] arr) {
		int x1 = 0, y1 = 0, x2 = arr.length - 1, y2 = arr[0].length - 1;
		while (x2 >= x1 && y2 >= y1) {
			for (int i = x1; i < x2; i++) {
				System.out.print(arr[y1][i] + " ");
			}
			for (int i = y1; i < y2; i++) {
				System.out.print(arr[i][x2] + " ");
			}
			for (int i = x2; i > x1; i--) {
				System.out.print(arr[y2][i] + " ");
			}
			for (int i = y2; i > y1; i--) {
				System.out.print(arr[i][x1] + " ");
			}
			x1++;
			y1++;
			x2--;
			y2--;
		}
	}
}
